package org.csu.mypetstore.api.controller.front;

import com.fasterxml.jackson.core.JsonProcessingException;
import org.apache.coyote.Request;
import org.csu.mypetstore.api.common.CommonResponce;
import org.csu.mypetstore.api.common.JwtTokenUtil;
import org.csu.mypetstore.api.entity.Cart;
import org.csu.mypetstore.api.entity.Item;
import org.csu.mypetstore.api.service.CartService;
import org.csu.mypetstore.api.vo.CartItemVO;
import org.csu.mypetstore.api.vo.CartVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import javax.xml.crypto.Data;
import java.util.*;

@CrossOrigin(origins = "http://localhost:8888",
        allowedHeaders = "*",
        methods = {RequestMethod.GET, RequestMethod.POST, RequestMethod.PUT, RequestMethod.DELETE, RequestMethod.OPTIONS},
        allowCredentials = "true")
@RestController
@RequestMapping("/cart/")
public class CartController {

    @Autowired
    CartService cartService;
    @Autowired
    JwtTokenUtil jwtTokenUtil;
//    前端从后端获取cart，后端从数据库查找对应的item合并成cart（并不直接打包存储到数据库里，只是在此停留）
    @GetMapping("{userid}")
    public CommonResponce<List<Cart>> getCart(@PathVariable String userid,@RequestHeader("Authorization") String token){
        try{
            String Testname=jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
            if (!Objects.equals(Testname, userid)){
                return CommonResponce.createForError(1,"你无权操作该用户信息");
            }
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
        return cartService.getCart(userid);
    }

    //添加购物车商品
    @PostMapping("items/{itemId}")
    public CommonResponce<Cart> insertItem(@PathVariable String itemId, @RequestHeader("Authorization") String token){
        try{
            String username=jwtTokenUtil.getUsernameFromToken(token.replace("Bearer ", ""));
            return cartService.addItem(username,itemId);
        } catch (Exception e) {
            return CommonResponce.createForError(1,"服务器异常");
        }
    }

    //删除item
    @DeleteMapping("items/{itemId}")
    public CommonResponce removeItem(@PathVariable String itemId,@RequestHeader("Authorization") String token){
        try{
            String username=jwtTokenUtil.getUsernameFromToken(token.replace("Bearer",""));
            return  cartService.removeItem(username,itemId);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    //更新购物车
    @PutMapping("items/{id}")
    public  CommonResponce<CartItemVO> updateQuantity(@PathVariable String id,
                                                      @RequestHeader("Authorization") String token,
                                                      @RequestBody Integer quantity){
//        String itemId=request.getid;
        try{
            String username=jwtTokenUtil.getUsernameFromToken(token.replace("Bearer",""));
            return cartService.updateQuantity(username,id,quantity);
        } catch (JsonProcessingException e) {
            throw new RuntimeException(e);
        }
    }
}
